package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.AppealLog;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.entity.Organization;
import com.mingqijia.gassafety.db.hangzhou.entity.AlertRecordSign;
import com.mingqijia.gassafety.db.mapper.AlertRecordSignMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.AlertRecordSignRequest;
import com.mingqijia.gassafety.webserver.request.SignRequest;
import com.mingqijia.gassafety.webserver.service.AlertRecordSignService;
import com.mingqijia.gassafety.webserver.service.AppealLogService;
import com.mingqijia.gassafety.webserver.service.HistoryAlarmService;
import com.mingqijia.gassafety.webserver.service.OrganizationService;
import com.mingqijia.gassafety.webserver.webSocket.WebSocketDpProcess;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 设备报警标记 服务实现类
 * </p>
 *
 * @author zhangfei
 * @since 2022-12-02
 */
@Service
@Slf4j
public class AlertRecordSignServiceImpl extends ServiceImpl<AlertRecordSignMapper, AlertRecordSign> implements AlertRecordSignService {


    @Autowired
    private  AlertRecordSignMapper alertRecordSignMapper;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    OrganizationService organizationService;
    
    @Autowired
    WebSocketDpProcess webSocketDpProcess;

    /**
     * 打标
     * @param req
     */
    @Override
    @Transactional
    public void sign(SignRequest req) {
        String spId = ApplicationUtils.getWorkingSpId();
        AlertRecordSign alertRecordSign = new AlertRecordSign();
        alertRecordSign.setAlertTime(req.getTime());
        alertRecordSign.setReportTime(DateUtil.parse(req.getTime()));
        alertRecordSign.setDealtRecord(req.getDealtRecord());
        alertRecordSign.setDealtResult(req.getDealtResult());
        alertRecordSign.setIMEI(req.getImei());
        alertRecordSign.setIsFinished(req.getIsFinished());
        alertRecordSign.setSpId(spId);
        alertRecordSignMapper.insert(alertRecordSign);
        //记录诉求表
        AppealLog appealLog = new AppealLog();
        appealLog.setAlarmBrokenId(req.getId());
        if (alertRecordSign.getIsFinished().equals(0)) {
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_4);
        } else {
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_5);
        }
        appealLog.setAppealResult(req.getDealtRecord());
        appealLog.setSpId(spId);
        appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
        appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
        log.info("新增报警诉求记录："+appealLog.toString());
        appealLogService.save(appealLog);
        LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
        historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
        HistoryAlarm historyAlarmLog = new HistoryAlarm();
        if (StringUtils.isNotEmpty(req.getValveBrokenInfo())) {
            historyAlarmLog.setValveBrokenInfo(req.getValveBrokenInfo());
        }
        historyAlarmLog.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
        historyAlarmLog.setAppealStatus(appealLog.getAppealStatus());
        historyAlarmLog.setAppealResult(appealLog.getAppealResult());
        historyAlarmLog.setUserName(appealLog.getUserName());
        historyAlarmLog.setUserAccount(appealLog.getUserAccount());
        historyAlarmLog.setAppealTime(appealLog.getCreatedAt());
        boolean historyAlarmResult = historyAlarmService.update(historyAlarmLog,historyAlarmWrapper);
        sendDpMessage();
        log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarmLog.toString());
    }

    /**
     * 查询
     *
     * @return
     */
    @Override
    public PageUtil<AlertRecordSign> query(AlertRecordSignRequest req) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<AlertRecordSign> alertRecordSigns =new ArrayList<>();
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        List<Organization> parentSps = organizationService.getParentIdBySpid(spId);
        if (ObjectUtil.isNotEmpty(parentSps)) {
           for (Organization pOrg:parentSps){
               if( !spIds.contains(pOrg.getParentId()) ){
                   spIds.add(pOrg.getParentId());
               }
           }
        }
        List<Organization> childSps = organizationService.getChildList(spId);
        if(ObjectUtil.isNotEmpty(childSps)){
            for (Organization cOrg:childSps){
                if( !spIds.contains(cOrg.getSpId()) ){
                    spIds.add(cOrg.getSpId());
                }
            }
        }
        log.info("查询spIds的数据:{}", StringUtils.join(spIds,","));
        Page pageHelper = PageHelper.startPage(req.getPage(), req.getPageSize());
        QueryWrapper<AlertRecordSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(AlertRecordSign::getAlertTime,req.getTime())
                .in(AlertRecordSign::getSpId,spIds)
                .eq(AlertRecordSign::getIMEI,req.getImei()).eq(AlertRecordSign::getIsDeleted,0)
                .orderByDesc(AlertRecordSign::getCreatedAt);
        alertRecordSigns = alertRecordSignMapper.selectList(queryWrapper);
        PageUtil pageInfo = new PageUtil(req.getPage(), req.getPageSize()
                ,pageHelper.getTotal(), alertRecordSigns);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signSync() {
        List<AlertRecordSign> alertRecordSigns = alertRecordSignMapper.signSync();
        log.info("alertRecordSigns:{}", JSONObject.toJSONString(alertRecordSigns));
        if (CollectionUtil.isNotEmpty(alertRecordSigns)) {
            alertRecordSigns.forEach(req -> {
                //记录诉求表
                AppealLog appealLog = new AppealLog();
                appealLog.setAlarmBrokenId(req.getAlarmBrokenId());
                if (req.getIsFinished().equals(0)) {
                    appealLog.setAppealStatus(Constants.APPEAL_STATUS_4);
                } else {
                    appealLog.setAppealStatus(Constants.APPEAL_STATUS_5);
                }
                appealLog.setAppealResult(req.getDealtRecord());
                appealLog.setSpId(req.getSpId());
                log.info("alertRecordSigns-新增报警诉求记录："+appealLog.toString());
                appealLogService.save(appealLog);
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarmLog = new HistoryAlarm();
                historyAlarmLog.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarmLog.setAppealStatus(appealLog.getAppealStatus());
                historyAlarmLog.setAppealResult(appealLog.getAppealResult());
                historyAlarmLog.setUserName(appealLog.getUserName());
                historyAlarmLog.setUserAccount(appealLog.getUserAccount());
                historyAlarmLog.setAppealTime(appealLog.getCreatedAt());
                boolean historyAlarmResult = historyAlarmService.update(historyAlarmLog,historyAlarmWrapper);
                log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarmLog.toString());
            });
        }
    }

    private void sendDpMessage(){
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            Map<String, String> params = new HashMap<>();
            params.put("source", "orderHandleFlag");
            webSocketDpProcess.redisTopicSendMsg(spId, JSONUtil.toJsonStr(params));
        }catch(Exception e){
            log.error("发送大屏消息",e);
        }
    }
}
